﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MethodWorx.Core.DomainModel;
using System.Web.Mvc;

namespace MethodWorx.Core.Mvc
{
    public class RepositoryModelBinder<T> : IModelBinder
        where T : AggregateRoot
    {
        private IRepositoryRegistry registry;

        public RepositoryModelBinder(IRepositoryRegistry registry)
        {
            this.registry = registry;
        }

        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            try
            {
                return ((IRepository<T>)registry.GetRepository(typeof(T)))[Guid.Parse(bindingContext.ValueProvider.GetValue(bindingContext.ModelName).AttemptedValue)];
            }
            catch(Exception ex)
            {
                return null;
            }
        }
    }
}
